import { Form, Button, Input, Modal, message, Radio, Checkbox } from 'antd'
import { useState, useImperativeHandle, useEffect } from 'react'
import { http } from '@/utils'
import { dict_data } from '@/dict'

// const { TextArea } = Input
const Addorupdatafreq = ((props) => {
  const [showModalOpen, setShowModalOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [freqType, setFreqType] = useState(null)
  const [title, setTitle] = useState(null)
  const [singleFreqList, setSingleFreqList] = useState([])
  const [factorListOpt, setFactorList] = useState([])
  const [freqId, setFreqId] = useState(null)
  const freqTypeOpt = dict_data[1011].map(item => { return { label: item.dictName, value: item.dictCode } })

  const configModalOpenOk = () => {
    setShowModalOpen(false)
  }
  const configModalOpenCancel = () => {
    form.resetFields()
    setShowModalOpen(false)
  }

  // 父组件调用打开模态框
  useImperativeHandle(props.onRef, () => {
    return {
      openModalOpen: openModalOpen,
    }
  })
  const openModalOpen = (data) => {
    form.resetFields()
    setTitle(data.id ? '编辑周期' : '添加周期')
    setFreqType(data.freqType)
    const factorList = data.factorList ? data.factorList.split(',').map(item => +item) : []
    const freqList = data.freq_List ? data.freq_List.split(',').map(item => +item) : []
    setFreqId(data.id)
    console.log(data, factorList, freqList)
    form.setFieldsValue({
      freqName: data.freqName || '',
      freqCode: data.freqCode || '',
      freqType: data.freqType || '',
      factorList: factorList,
      freqList: freqList,
    })
    setShowModalOpen(true)
  }
  /* 使用hooks 更新form组件 */
  const [form] = Form.useForm()
  const addOrUpdateFactorConfig = async (values) => {
    const data = {
      id: freqId,
      ...values,
      factorList: values.freqType === 1 ? values.factorList.join() : null,
      freqList: values.freqType === 2 ? values.freqList.join() : null,
    }
    console.log(data)
    setLoading(true)
    const res = await http.post('/alarm/deliversign/addOrUpdateFreqConfig', data)
    setLoading(false)
    message.success(res.body)
    setShowModalOpen(false)
    props.changeConfigModal('child msg')
  }
  const freqTypeOnchange = (val) => {
    setFreqType(val)
  }
  useEffect(() => {
    const getList = async () => {
      const res = await http.post('/alarm/deliversign/getAllFreqByType', { freqType: 1 })
      console.log('单周期列表-', res.body)
      const list = res.body.map(item => {
        return {
          label: item.freqName,
          value: item.id,
          key: item.id
        }
      })
      setSingleFreqList(list)
    }
    const getFactor = async () => {
      const res = await http.post('/alarm/deliversign/getFactorConfigByPage', { pageNum: 1, pageSize: 999, factorType: 1 })
      console.log('打分因子列表-', res.body)
      const list = res.body.list.map(item => ({
        value: item.id,
        key: item.id,
        label: item.factorName
      }))
      setFactorList(list)
    }
    if (showModalOpen) {
      getList()
      getFactor()
    }
  }, [showModalOpen])
  return (
    <>
      {/* forceRender Modal未弹出时强制渲染  处理form hooks 动态赋值问题 */}
      <Modal
        title={title}
        open={showModalOpen}
        onOk={configModalOpenOk}
        onCancel={configModalOpenCancel}
        footer={false}
        width={800}
      >
        <Form
          form={form}
          colon={false}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={addOrUpdateFactorConfig}
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 21 }}
          initialValues={{}}
        >
          <Form.Item
            label="周期名称"
            name="freqName"
            rules={[
              {
                required: true,
                message: '请输入周期名称',
              }
            ]}>
            <Input
              allowClear
              placeholder='请输入周期名称'
              style={{ width: 260 }}
            />
          </Form.Item>
          <Form.Item
            label="周期标识"
            name="freqCode"
            rules={[
              {
                required: true,
                message: '请输入周期标识',
              }
            ]}>
            <Input
              allowClear
              placeholder='请输入周期标识'
              style={{ width: 260 }}
            />
          </Form.Item>
          <Form.Item
            label="周期类型"
            name="freqType"
            rules={[
              {
                required: true,
                message: '请选择周期类型',
              }
            ]}
          >
            <Radio.Group options={freqTypeOpt} onChange={(e) => freqTypeOnchange(e.target.value)} />
          </Form.Item>

          {
            // 单周期
            freqType === 1 ? <Form.Item label="" name="factorList" style={{ paddingLeft: '20px' }}>
              <Checkbox.Group options={factorListOpt} />
            </Form.Item> : ''
          }
          {
            // 复合周期
            freqType === 2 ? <Form.Item label="" name="freqList" style={{ paddingLeft: '20px' }}>
              <Checkbox.Group options={singleFreqList} />
            </Form.Item> : ''
          }
          <Form.Item label=" ">
            <Button htmlType="submit" type="primary" loading={loading}>
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal >
    </>
  )
})
export default Addorupdatafreq